package com.triones.ljr.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtil;
import com.triones.ljr.entity.bo.DeclareAuditBO;
import com.triones.ljr.entity.bo.DeclareAuditParams;
import com.triones.ljr.entity.bo.DeclareSysAuditBO;
import com.triones.ljr.entity.dto.DeclareAuditDO;
import com.triones.ljr.entity.dto.EnterpriseDO;
import com.triones.ljr.entity.dto.PolicyItemDO;
import com.triones.ljr.entity.dto.SsEnterpriseDO;
import com.triones.ljr.entity.vo.*;
import com.triones.ljr.mapper.DeclareAuditMapper;
import com.triones.ljr.mapper.EnterpriseMapper;
import com.triones.ljr.mapper.PolicyItemMapper;
import com.triones.ljr.mapper.SsEnterpriseMapper;
import com.triones.ljr.service.DeclareAuditService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 申报审核
 */
@Service
@RequiredArgsConstructor
public class DeclareAuditServiceImpl implements DeclareAuditService {

    private final DeclareAuditMapper declareAuditMapper;

    private final EnterpriseMapper enterpriseMapper;

    private final PolicyItemMapper policyItemMapper;

    private final SsEnterpriseMapper ssEnterpriseMapper;

    @Override
    public boolean add(DeclareAuditBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        PolicyItemDO policyItemDO = policyItemMapper.selectOne(new LambdaQueryWrapper<PolicyItemDO>()
            .eq(PolicyItemDO::getId, bo.getPolicyItemId())
            .eq(PolicyItemDO::getIsDel, "0")
            .last("limit 1"));
        if (policyItemDO == null) {
            throw new ServiceException("政策细则不存在");
        }
        DeclareAuditDO declareAudit = BeanUtil.toBean(bo, DeclareAuditDO.class);
        declareAudit.setWxUserId(loginUser.getUserId());
        EnterpriseVO enterprise = enterpriseMapper.selectVoOne(new LambdaQueryWrapper<EnterpriseDO>()
            .eq(EnterpriseDO::getWxUserId, loginUser.getUserId())
            .eq(EnterpriseDO::getStatus, "1")
            .orderByDesc(EnterpriseDO::getCreateTime)
            .last("limit 1"));
        if (enterprise == null) {
            throw new ServiceException("未查询到当前用户有效的企业信息!");
        }
        SsEnterpriseDO ssEnterpriseDO = ssEnterpriseMapper.selectOne(new LambdaQueryWrapper<SsEnterpriseDO>().eq(SsEnterpriseDO::getEnterpriseName, enterprise.getName())
            .eq(SsEnterpriseDO::getIsDel, "0")
            .last("limit 1"));
        if (ssEnterpriseDO == null) {
            throw new ServiceException("未查询到当前用户有效的企业信息!");
        }

        DeclareAuditDO declareAuditDO = declareAuditMapper.selectOne(new LambdaQueryWrapper<DeclareAuditDO>()
            .eq(DeclareAuditDO::getDel, 0)
            .eq(DeclareAuditDO::getWxUserId, loginUser.getUserId())
            .eq(DeclareAuditDO::getEid, enterprise.getId())
            .eq(DeclareAuditDO::getPolicyItemId, policyItemDO.getId())
            .orderByDesc(DeclareAuditDO::getApplyTime).last("limit 1"));
        if (declareAuditDO != null) {
            throw new ServiceException("当前政策申报已存在，请勿重复提交申报！");
        }

        declareAudit.setPrimaryUserId(1950417573700726785L);
        declareAudit.setVerifyUserId(1950417573700726785L);
        declareAudit.setApplyTime(DateUtil.getDateTimeString());
        declareAudit.setEid(enterprise.getId());
        return declareAuditMapper.insert(declareAudit) > 0;
    }

    @Override
    public TableDataInfo<CustomDeclareAuditVO> pageList(DeclareAuditParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        Page<CustomDeclareAuditVO> result = declareAuditMapper.selectPageList(pageQuery.build(), params);
        return TableDataInfo.build(result);
    }

    @Override
    public boolean audit(DeclareSysAuditBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        DeclareAuditDO declareAuditDO = declareAuditMapper.selectById(bo.getId());
        if (declareAuditDO == null) {
            throw new ServiceException("没有查询到申报信息!");
        }
        declareAuditDO.setPrimaryUserId(loginUser.getUserId());
        declareAuditDO.setPrimaryUserName(loginUser.getUsername());
        declareAuditDO.setPrimaryStatus(bo.getStatus());
        declareAuditDO.setPrimaryRemark(bo.getFailedRemark());
        declareAuditDO.setPrimaryTime(DateUtil.getDateTimeString());
        declareAuditDO.setIsExist(bo.getIsExist());
        declareAuditDO.setQuitTime(bo.getQuitTime());
        declareAuditDO.setIsHonest(bo.getIsHonest());
        if ("1".equals(bo.getStatus())) {
            declareAuditDO.setStatus("0");
        } else {
            declareAuditDO.setStatus("2");
            declareAuditDO.setFailedRemark(bo.getFailedRemark());
        }
        declareAuditDO.setUpdateTime(DateUtil.getDateTimeString());
        return declareAuditMapper.updateById(declareAuditDO) > 0;
    }

    @Override
    public TableDataInfo<CustomDeclareAuditVO> apiDeclarePageList(String keyword, String status, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.eq("da.wx_user_id", loginUser.getUserId())
            .eq("da.del", "0")
            .eq(ObjectUtil.isNotEmpty(status), "da.status", status)
            .like(ObjectUtil.isNotEmpty(keyword), "pi.item_name", keyword)
            .orderByDesc("da.apply_time");
        Page<CustomDeclareAuditVO> result = declareAuditMapper.apiDeclarePageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public CustomDeclareAuditVO declareDetail(Long id) {
        return declareAuditMapper.declareDetail(id);
    }

    @Override
    public boolean fulfill(DeclareSysAuditBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        DeclareAuditDO declareAuditDO = declareAuditMapper.selectById(bo.getId());
        if (declareAuditDO == null) {
            throw new ServiceException("没有查询到申报信息!");
        }
        declareAuditDO.setVerifyStatus("1");
        declareAuditDO.setVerifyTime(DateUtil.getDateTimeString());
        declareAuditDO.setVerifyUserId(loginUser.getUserId());
        declareAuditDO.setVerifyUserName(loginUser.getUsername());
        declareAuditDO.setEvidence(bo.getEvidence());
        declareAuditDO.setUpdateTime(DateUtil.getDateTimeString());
        declareAuditDO.setStatus("1");
        return declareAuditMapper.updateById(declareAuditDO) > 0;
    }

    @Override
    public List<CustomDeclareAuditVO> selectListByIds(List<Long> ids) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        return declareAuditMapper.selectListByIds(loginUser.getUserId(),ids);
    }

    @Override
    public boolean edit(DeclareAuditBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        PolicyItemDO policyItemDO = policyItemMapper.selectOne(new LambdaQueryWrapper<PolicyItemDO>()
            .eq(PolicyItemDO::getId, bo.getPolicyItemId())
            .eq(PolicyItemDO::getIsDel, "0")
            .last("limit 1"));
        if (policyItemDO == null) {
            throw new ServiceException("政策细则不存在");
        }
        DeclareAuditDO declareAudit = BeanUtil.toBean(bo, DeclareAuditDO.class);
        declareAudit.setWxUserId(loginUser.getUserId());
        EnterpriseVO enterprise = enterpriseMapper.selectVoOne(new LambdaQueryWrapper<EnterpriseDO>()
            .eq(EnterpriseDO::getWxUserId, loginUser.getUserId())
            .eq(EnterpriseDO::getStatus, "1")
            .orderByDesc(EnterpriseDO::getCreateTime)
            .last("limit 1"));
        if (enterprise == null) {
            throw new ServiceException("未查询到当前用户有效的企业信息!");
        }
        SsEnterpriseDO ssEnterpriseDO = ssEnterpriseMapper.selectOne(new LambdaQueryWrapper<SsEnterpriseDO>().eq(SsEnterpriseDO::getEnterpriseName, enterprise.getName())
            .eq(SsEnterpriseDO::getIsDel, "0")
            .last("limit 1"));
        if (ssEnterpriseDO == null) {
            throw new ServiceException("未查询到当前用户有效的企业信息!");
        }
        DeclareAuditDO declareAuditDO = declareAuditMapper.selectById(bo.getId());
        if (declareAuditDO == null) {
            throw new ServiceException("没有查询到有效的申报信息！");
        }
        if (declareAuditDO.getStatus().equals("0")) {
            throw new ServiceException("当前政策申报正在审核中，不允许修改！");
        } else if (declareAuditDO.getStatus().equals("1")) {
            throw new ServiceException("当前政策申报已通过，不允许修改！");
        }
        declareAuditDO.setTel(bo.getTel());
        declareAuditDO.setCommitment(bo.getCommitment());
        declareAuditDO.setOperateImg(bo.getOperateImg());
        declareAuditDO.setBankName(bo.getBankName());
        declareAuditDO.setBankAccount(bo.getBankAccount());
        declareAuditDO.setCardHolding(bo.getCardHolding());
        declareAuditDO.setPrimaryStatus("0");
        declareAuditDO.setPrimaryRemark("");
        declareAuditDO.setStatus("0");
        declareAuditDO.setFailedRemark("");
        return declareAuditMapper.updateById(declareAuditDO) > 0;
    }

    @Override
    public boolean remove(Long id) {
        DeclareAuditDO declareAuditDO = declareAuditMapper.selectById(id);
        if (declareAuditDO == null) {
            throw new ServiceException("没有查询到申报信息!");
        }
        declareAuditDO.setDel("1");
        return declareAuditMapper.updateById(declareAuditDO) > 0;
    }
}
